package com.xiao.common.util;





import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

/**
 * @Author xiaoxiaoping
 * @Date 2019/11/4
 */
@Component
public class AESUtil {
    private static final String KEY_ALGORITHM = "AES";
    private static final String DEFAULT_CIPHER_ALGORITHM = "AES/ECB/PKCS5Padding";//默认的加密算法
    private static final String PASS_WORD = "xiaoping";
    private  final Logger logger = (Logger) LoggerFactory.getLogger(this.getClass());

    /**
     * AES 加密操作
     * @param content
     * @return
     */
    public  String encrypt(String content){
        try {
            Cipher cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM);//创建密码器
            byte[] byteContent = content.getBytes("utf-8");
            cipher.init(Cipher.ENCRYPT_MODE,getSecretKey());
            byte[] result = cipher.doFinal(byteContent);
            return parseByte2HexStr(result);
        } catch (Exception e) {
            e.printStackTrace();
            logger.info(e.getMessage());
        }
        return null;
    }

    /**
     * 解密操作
     * @param content
     * @return
     */
    public  String decrypet(String content){
        try {
            Cipher cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM);
            //使用密钥初始化，设置解密模式
            cipher.init(Cipher.DECRYPT_MODE,getSecretKey());
            //执行操作
            byte[] result = cipher.doFinal(parseHexStr2Byte(content));
            return new String(result,"utf-8");
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e.getMessage());
        }
        return null;
    }

    private  SecretKey getSecretKey() {
        KeyGenerator kg = null;
        try {
            kg = KeyGenerator.getInstance(KEY_ALGORITHM);
            //AES 要求密钥长度为128
            kg.init(128,new SecureRandom(PASS_WORD.getBytes()));
            //生成一个密钥
            SecretKey secretKey = kg.generateKey();
            //转化为AES专用密钥
            return new SecretKeySpec(secretKey.getEncoded(),KEY_ALGORITHM);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            logger.error(e.getMessage());
        }
        return null;
    }

    /**
     * 字符串转16进制
     * @param buf
     * @return
     */
    private  String parseByte2HexStr(byte[] buf) {
        StringBuffer sb = new StringBuffer();

        for(int i = 0; i < buf.length; ++i) {
            String hex = Integer.toHexString(buf[i] & 255);
            if (hex.length() == 1) {
                hex = '0' + hex;
            }

            sb.append(hex.toUpperCase());
        }

        return sb.toString();
    }

    /**
     * 16进制转字符串
     * @param hexStr
     * @return
     */
    private  byte[] parseHexStr2Byte(String hexStr) {
        if (hexStr.length() < 1) {
            return null;
        } else {
            byte[] result = new byte[hexStr.length() / 2];

            for(int i = 0; i < hexStr.length() / 2; ++i) {
                int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), 16);
                int low = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2), 16);
                result[i] = (byte)(high * 16 + low);
            }

            return result;
        }
    }

    public static void main(String[] args) {
        AESUtil aesUtil = new AESUtil();
        String s = "13508125658";
        System.out.println("s:" + s);
        String s1 = aesUtil.encrypt(s);
        System.out.println("s1:" + s1);
        String s2 = aesUtil.decrypet(s1);
        System.out.println("s2:" + s2);
    }
}
